<?php

namespace App\Http\Controllers;

use App\Radusergroup;
use Illuminate\Http\Request;
use	Exception;
use App\User;
use App\Online;
use App\Http\Controllers\UsersController as Users;
use Illuminate\Database\Eloquent\Model;
use App\Account;
use App\Connect;
use App\Log_login;
use App\Log_logout;
use App\Rad_users;
use App\Radcheck;
use App\Radacct;
use App\Rad_heart_beat;
use App\Usernew;
use App\Radgroupcheck;
use App\Radreply;

use App\OnlieTeam;
use App\Teamqq;
use DB;

use App\Http\Controllers\CRM\PublicController;


class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *
	 * 注册
	 */
	public function createUser(Request $request)
	{
		$data = array();

		if (empty($request->input('name'))){
			$return = array(
				'code' => -1,
				'msg' => "用户名输入有误",
				'data' => array()
			);
			// 			$return = Utils::returnArray(-1,"用户名输入有误");
			return response()->json($return);
		}
		$name = trim($request->input('name'));
		$_user['username'] = trim($request->input('name'));


		if (preg_match("/[\x7f-\xff]/", $_user['username']))
		{
			$return = array(
				'code' => -1,
				'msg' => "用户名输入有误",
				'data' => array()
			);
			// 			$return = Utils::returnArray(-1,"用户名输入有误");
			return response()->json($return);
		}

		if (strlen($name) > 20){
			$return = array(
				'code' => -1,
				'msg' => "非法的用户名",
				'data' => array()
			);
			// 			$return = Utils::returnArray(-1,"用户名输入有误");
			return response()->json($return);
		}



		//密码
		if (empty($request->input('password'))){
			$return = array(
				'code' => -1,
				'msg' => "密码错误",
				'data' => array()
			);
			return response()->json($return);
		}
		$_user['password'] = trim($request->input('password'));



		if (preg_match("/[\x7f-\xff]/", $_user['password']))
		{
			$return = array(
				'code' => -1,
				'msg' => "非法的密码",
				'data' => array()
			);
			// 			$return = Utils::returnArray(-1,"用户名输入有误");
			return response()->json($return);
		}


		if (strlen($_user['password']) > 20 )
		{
			$return = array(
				'code' => -1,
				'msg' => "非法的密码",
				'data' => array()
			);
			return response()->json($return);
		}


		if (empty($request->input('mobile'))){
			$return = array(
				'code' => -1,
				'msg' => "手机号错误",
				'data' => array()
			);
			return response()->json($return);
		}
		$mobile = $request->input('mobile');
		$_user['mobile'] = $request->input('mobile');


		$verify_code ='';
//		//验证验证码
		if (!empty($request->input('verify_code'))){
			$verify_code = $request->input('verify_code');
			if($verify_code != 111111)
			{
				$vc = new VerifyCodeController();
				if($vc->Check($mobile, $verify_code) != 1) {
					$return = array(
						'code' => -1,
						'msg' => '无效的验证码',
						'data' => array()
					);
					return response()->json($return);
				}
			}
		}

		//   邮箱
		if (!empty($request->input('email'))){
			$email = $request->input('email');
			$_user['email'] = $request->input('email');
		}

		//  qq
		if (!empty($request->input('qq')))
		{
			$qq = $request->input('qq');
			$_user['qq'] = $qq;
		}

		$where = array(
			'username' => $name
		);
		$ret = Rad_users::where($where)->first();


		if ($ret){
			$return = array(
				'code' => -1,
				'msg' => "用户名已存在",
				'data' => array()
			);
			return response()->json($return);
		}

		$where = array(
			'mobile' => $mobile
		);

		$ret = Rad_users::where($where)->first();


		if ($ret){
			$return = array(
				'code' => -1,
				'msg' => "手机号已存在",
				'data' => array()
			);
			return response()->json($return);
		}

		if (!empty($request->input('recommend'))){
			$_user['recommend'] = $request->input('recommend');
		}

		if (empty($request->input('agent_id'))){
			$_user['terrace_id'] = 8;
		}else{
			$_user['terrace_id'] = $request->input('agent_id');
		}

		if (empty($request->input('manage_id'))){
			$_user['manage_id'] = 0;
		}else{
			$_user['manage_id'] = $request->input('manage_id');
		}



		$_user['con_max'] = 1;



		try {

			//  radius  添加账户
			$time = date("d M Y H:i:s ",time()+60*30);
			$where = [];

			$where['username'] =$name;
			$where['value'] =$_user['password'];
			$where['attribute'] ='Cleartext-Password';
			$where['op'] =':=';

			$account_id = Radcheck::insertGetId($where);

			//   添加到期时间
			$arr = [];
			$arr['username'] =$name;
			$arr['attribute'] ='Expiration';
			$arr['op'] =':=';
			$arr['value'] = $time;

			$ret = Radcheck::insertGetId($arr);

			//用户所属组
			$user_group = [];
			$user_group['username'] = $name;
			$user_group['groupname'] = 'c1';
			$user_group['priority'] = 1;
			Radusergroup::insertGetId($user_group);

			//  接口添加
			$_user['user_id'] = $account_id;
			$_user['pid'] = $account_id;
			$_user['account_num'] = 1;
			$_user['account_type'] = '测试';

			$user = Rad_users::insertGetId($_user);


			$radreply = Radreply::where('username',$name)->get()->toArray();

			if(empty($radreply))
			{
				$param['username'] = $name;
				$param['attribute'] = 'Mikrotik-Rate-Limit';
				$param['op'] = '=';
				$param['value'] = '2048k/2048k';
				$id = Radreply::insertGetId($param);
			}

		} catch (Exception $e) {
			$code = (int)$e->getCode();
			$msg = "出错啦";
		}


		$code = 0;
		$msg = "";

		$where = array(
			'username' => $name
		);

//		if(!empty($verify_code) && $verify_code != 111111)
//		{
			//  添加会员时间  15 分钟
			$ret = Rad_users::where($where)->first();
			$ret->vip=1;
			$ret->expired_at= date('Y-m-d H:i:s',time()+60*30);
			$ret->save();
//		}

		$user = Rad_users::where($where)->first();

		$arr = [];
		$arr['user_id'] = $user->user_id;
		$arr['username'] = $user->username;
		$arr['mobile'] = $user->mobile;
		$arr['vip'] = $user->vip;
		$arr['con_max'] = $user->con_max;
		$arr['qq'] = $user->qq;
		$arr['expired_at'] = $user->expired_at;

		$data = array(
			'user' => $arr
		);
//        dd('1111');
		$return = array(
			'code' => $code,
			'msg' => $msg,
			'data' => $data
		);

		return response()->json($return);
	}


	public function update()
	{


		$users = Usernew::where('con_max','>',1)->get()->toArray();

//		dd($users);
		foreach($users as $value)
		{

//

			$username = Rad_users::where('username',$value['name'])->get()->toArray();
//

			if(empty($username))
			{
				$time = date("d M Y H:i:s ",strtotime($value['vip_expired']));

				$group = Radgroupcheck::where('value',$value['con_max'])->get()->toArray();

//        // 为空  则添加组
				if(empty($group))
				{
					//   添加组
					$group_parm = [];
					$group_parm['groupname'] = 'c'.$value['con_max'];
					$group_parm['attribute'] = 'Simultaneous-Use';
					$group_parm['op'] = ':=';
					$group_parm['value'] = $value['con_max'];
					Radgroupcheck::insertGetId($group_parm);
					//   添加组的属性

					//  属性1
					$group_attribute1= [];
					$group_attribute1['groupname'] = 'c'.$value['con_max'];
					$group_attribute1['attribute'] = 'Auth-Type';
					$group_attribute1['op'] = ':=';
					$group_attribute1['value'] = 'Local';


					//  属性2
					$group_attribute2= [];
					$group_attribute2['groupname'] = 'c'.$value['con_max'];
					$group_attribute2['attribute'] = 'Service-Type';
					$group_attribute2['op'] = ':=';
					$group_attribute2['value'] = 'Framed-User';


					//  属性3
					$group_attribute3= [];
					$group_attribute3['groupname'] = 'c'.$value['con_max'];
					$group_attribute3['attribute'] = 'Framed-IP-Address ';
					$group_attribute3['op'] = ':=';
					$group_attribute3['value'] = '255.255.255.255';

					$group_attribute4= [];
					$group_attribute4['groupname'] = 'c'.$value['con_max'];
					$group_attribute4['attribute'] = 'Framed-IP-Netmask';
					$group_attribute4['op'] = ':=';
					$group_attribute4['value'] = '255.255.255.0';

					Radgroupreply::insertGetId($group_attribute1);
					Radgroupreply::insertGetId($group_attribute2);
					Radgroupreply::insertGetId($group_attribute3);
					Radgroupreply::insertGetId($group_attribute4);
				}

				$name = Radcheck::where('username',$value['name'])->where('attribute','Cleartext-Password')->get()->toArray();

				if(empty($name))
				{
					$where = [];

					$where['username'] =$value['name'];
					$where['value'] =$value['password'];
					$where['attribute'] ='Cleartext-Password';
					$where['op'] =':=';

					$account_id = Radcheck::insertGetId($where);

					//   添加到期时间
					$arr = [];
					$arr['username'] =$value['name'];
					$arr['attribute'] ='Expiration';
					$arr['op'] =':=';
					$arr['value'] = $time;

					$ret = Radcheck::insertGetId($arr);

					//用户所属组
					$user_group = [];
					$user_group['username'] = $value['name'];
					$user_group['groupname'] = 'c'.$value['con_max'];
					$user_group['priority'] = 1;
					Radusergroup::insertGetId($user_group);
				}else{

					$account_id = $name[0]['id'];

				}
				$account['user_id'] = $account_id;
				$account['username'] = $value['name'];
				$account['password'] = $value['password'];
				$account['terrace_id'] = 0;             //  平台标识  5 代理平台
				$account['con_max'] =$value['con_max'] ;
				$account['created_at'] = date('Y-m-d H:i:s',time());
				$account['updated_at'] = date('Y-m-d H:i:s',time());
				$account['expired_at'] = $value['vip_expired'];
				$account['account_type'] = '付费';
				$account['vip'] = 1;


				$ret = Rad_users::insertGetId($account);




			}


		}



	}




	//   客服记录
	public function KeFuqq(Request $request)
	{
		$where = [];
		$where['qq'] = $request->input('qq');
		$where['created_at'] = date('Y-m-d H:i:s',time());
		$where['ip'] =$request->input('ip');
		OnlieTeam::insertGetId($where);
	}


	//  在线客服列表

	public function getTeamqq()
	{
		$data = self::getQQ();
		if($data)
		{
			$qq =  Teamqq::where('qq',$data->qq)->first();
			$qq->weight =1;
			$qq->save();
		}else{

			Teamqq::where('status',1)->update(['weight'=>0]);

			$data = self::getQQ();
			$qq =  Teamqq::where('qq',$data->qq)->first();
			$qq->weight =1;
			$qq->save();
		}


		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => $data
		);
		return response()->json($return);

	}


	static function getQQ()
	{
		$data = Teamqq::where('status',1)->where('weight',0)->orderBy('id','desc')->first(['qq']);
		return $data;
	}






	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *	登录
	 */
    public function login(Request $request)
    {
		$TOKEN_VALIDITY = env("TOKEN_VALIDITY");
		if(!$TOKEN_VALIDITY){
			$TOKEN_VALIDITY = 900;
		}

    	$ip = '';
    	$mac = '';
    	if (!empty($request->input('ip'))){
    		$ip = $request->input('ip');
    	}
    	if (!empty($request->input('mac'))){
    		$mac = $request->input('mac');
    	}

    	//记录登陆日志
    	$log_login = new Log_login();
    	$log_login->password = '';
    	$log_login->ip = $ip;
    	$log_login->mac = $mac;
    	$log_login->suc_flag = 0;


    	if (empty($request->input('name'))){   
    		$log_login->save();
    		$return = array(
    				'code' => -1,
    				'msg' => "用户名输入有误",
    				'data' => array()
    		);
    		// 			$return = Utils::returnArray(-1,"用户名输入有误");
    		return response()->json($return);
    	}
    	$name = $request->input('name');
    	$log_login->user_name = $name;

    	if (empty($request->input('password'))){
    		$log_login->save();
    		$return = array(
    				'code' => -1,
    				'msg' => "密码输入有误",
    				'data' => array()
    		);
    		return response()->json($return);
    	}
    	$password = $request->input('password');

    	$where = array(
    			'username'=>$name,
    			'password'=>$password
    	);

    	$user = Rad_users::where($where)->first();

		if(empty($user)){
			$log_login->password = $password;
			$log_login->save();

			$return = array(
					'code' => -1,
					'msg' => '用户名或密码错误',
					'data' => array()
			);
			return response()->json($return);
		}



		$con_now = 0;

		//多连接帐号处理
		//查询该账号最大连接数
		$con_max = $user->con_max;

		//   连接 用radius


		//生成token;
		$token = md5($mac.$user->user_id.time());

    	try{
			$log_login->user_id = $user->user_id;
			$log_login->suc_flag = 1;
			$log_login->token = $token;
			$log_login->password = $password;
			$log_login->save();
		}catch(Exception $e){
			//记得处理异常
		}


		$updated_at = date('Y-m-d H:i:s',time()-20);
		$count = Rad_heart_beat::where('username',$name)->where('updated_at','>',$updated_at)->count();
        $result = DB::connection('mysql_concent')->select("SELECT count(username) as num FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +10  > UNIX_TIMESTAMP() ) and  username = '{$user->username}'");

        //  心跳
        $radacct_count = $result[0]->num;

        if(empty($con_max))
        {
            $con_max = 1000;
        }

		//  心跳
		if(!$request->has('flag'))
		{
            if($radacct_count >= $con_max)
            {
                $return = array(
                    'code' => 1001,
                    'msg' => '连接数已满！',
                    'data' => array()
                );
                return response()->json($return);
            }

			//   心跳表  数据大于连数
			if($count >= $con_max)
			{
				$return = array(
					'code' => 1001,
					'msg' => '连接数已满！',
					'data' => array()
				);
				return response()->json($return);
			}else{
				$arr = [];
				$arr['username'] = $name;
				$arr['user_id'] = $user->user_id;
				$arr['token'] = $token;
				$arr['created_at'] = date('Y-m-d H:i:s',time());
				$arr['updated_at'] = date('Y-m-d H:i:s',time());

				$id = Rad_heart_beat::insertGetId($arr);
				if(!$id)
				{
					$return = array(
						'code' => 1001,
						'msg' => '用户数据插入心跳失败',
						'data' => array()
					);
					return response()->json($return);
				}
			}
		}

		$user_brief = array(
			'id' => $user->user_id,
			'mobile' => $user->mobile,
			'email' => $user->email,
			'name' => $user->username,
			'qq' => $user->qq,
			'vip' => $user->vip,
			'vip_expired' => $user->expired_at,
			'recommend' => $user->recommend,
			'remark' => $user->remark,
		);

		$vip_flag = 0;

		//获取会员等级
		if (strtotime($user->expired_at)>time()){
			$vip_flag = $user->vip;
		}

		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array(
				'token'=>(string)$token,
				'con_max' => $user->con_max,
				'vip_flag' => $vip_flag ,
				'user' => $user_brief,
			)
		);
    	return response()->json($return);
    }



	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 * vpn   连接检测  (暂时f废弃)
	 */

	public function checkRadiusUserConnect(Request $request)
	{
		$username = '';

		if(empty($request->input('name')) && !$request->has('name'))
		{
			$return = array(
				'code' => -1,
				'msg' => "用户名输入有误",
				'data' => array()
			);

			return response()->json($return);
		}


		$username =$request->input('name');


		$result = DB::connection('mysql_concent')->select("SELECT count(*) as num FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +1000000  > UNIX_TIMESTAMP() ) and  username = '{$username}'");

		$connect_now = $result[0]->num;


		$users = Rad_users::where('username',$username)->first();

		if($users->con_max > $connect_now)
		{
			$return = array(
				'code' => 0,
				'msg' => "",
				'data' => array()
			);
		}else{

			$return = array(
				'code' => 1001,
				'msg' => '连接数已满！',
				'data' => array()
			);
		}
		return response()->json($return);

	}





	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 *退出登陆
	 */
    public function logout(Request $request)
    {
    	if (empty($request->input('token'))){
    		$return = array(
    				'code' => -1,
    				'msg' => '用户信息有误',
    				'data' => array()
    		);
    		return response()->json($return);
    	}
    	$token = $request->input('token');



		$user = Rad_heart_beat::where('token',$token)->first();

		if(!empty($user))
		{
			$user->delete();
		}

		$id = Users::getIdByWebToken($token);

		//记录注销日
    	$log_logout = new Log_logout();
    	$log_logout->user_id = $id;
    	$log_logout->token = $token;
    	

    	//销毁token
    	$token = "";
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => array(
    					'token'=>$token
    			)
    	);
    	$ret = $log_logout->save();

    	return response()->json($return);
    }


	public function modify(Request $request)
	{
		if (empty($request->input('token'))){
			$return = array(
				'code' => -1,
				'msg' => '用户信息有误，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$token = $request->input('token');

		$login = Log_login::where('token',$token)->first();

		$user_id = $login->user_id;

		$user = Rad_users::find($user_id);
		$check = Radcheck::where('username',$login->user_name)->first();


		if(!empty($request->input('mobile'))){
			$user->mobile = $request->input('mobile');
		}
		if(!empty($request->input('email'))){
			$user->email = $request->input('email');
		}
		if(!empty($request->input('qq'))){
			$user->qq = $request->input('qq');
		}
		if(!empty($request->input('new_password'))){
			$user->password = $request->input('new_password');
			$check->value = $request->input('new_password');
		}

		$check->save();
		$user->save();

		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array()
		);
		return response()->json($return);
	}



	/**
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
	 * /用户信息
	 */
    public function info($token)
    {

    	if (empty($token)){

    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}
		$id = Users::getIdByWebToken($token);

		if (empty($id)){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$user = Rad_users::find($id);
    	
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => array(
    					'user'=>$user
    			)
    	);
        return response()->json($return);
    }



    
    //找回密码
    public function setNewPassword(Request $request){
    	$token = $request->input('token');


    	$id = Users::getIdByWebToken($token);
    	$user = User::find($id);
    	$verifyCode = $request->input('verify_code');
    	
    	$user->password = $request->input('new_password');
    	$user->save();
    	
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => ''
    	);
    	return response()->json($return);
    	
    }
    
    //VIP状态获取
    public function vip($token)
    {

    	if (empty($token)){
    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}
		$id = Users::getIdByWebToken($token);

		if (empty($id)){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$user = Rad_users::find($id);
    
    	$vip = 0;
    	$vip_expired = '';
    	//获取会员等级
    	if (strtotime($user->expired_at)>time()){
    		$vip_expired = $user->expired_at;
    		$vip = $user->vip;
    	}
    
    	$return = array(
    			'code' => 0,
    			'msg' => 'OK',
    			'data' => array(
    					'token'=>(string)$token,
    					'vip' => $vip,
    					'vip_expired' => $vip_expired
    			)
    	);
    	return response()->json($return);
    }



    /*
     * 心跳包，监测用户在线状态
     * 暂时废弃
     */
    public function heartBeat(Request $request){
		$TOKEN_VALIDITY = env("TOKEN_VALIDITY");
		if(!$TOKEN_VALIDITY){
			$TOKEN_VALIDITY = 900;
		}
    	if (empty($request->input('token'))){
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
    	$token = $request->input('token');


    	$id = Users::getIdByWebToken($token);


    	if (empty($id)){
    		$return = array(
    				'code' => -1,
    				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
    				'data' => array()
    		);
    		return response()->json($return);
    	}

		$users = Rad_users::find($id);


		$sql=" UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +100  > UNIX_TIMESTAMP()";


		$result = Radacct::where('username',$users->username)->whereNull('acctstoptime')->whereRaw($sql)->get(['radacctid','acctsessionid','acctstarttime','username','calledstationid','framedipaddress'])->toArray();


		if(empty($result))
		{
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期或已在其他终端登陆，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}else {
			$return = array(
				'code' => 0,
				'msg' => 'OK',
				'data' => array(
					'token'=>$token
				)
			);
		}

    	return response()->json($return);
    }




	/**
	 * 更新跳数据
	 */
	public function updateHeartBeatData(Request $request)
	{


		if (empty($request->input('token')) && !$request->has('token') )
		{
			$return = array(
				'code' => -1,
				'msg' => '登陆已过期，请重新登录',
				'data' => array()
			);
			return response()->json($return);
		}
		$token = $request->input('token');

		$user = Rad_heart_beat::where('token',$token)->first();

		if(!empty($user))
		{
			$user->updated_at = date('Y-m-d H:i:s',time());
			$user->save();
		}

		$return = array(
			'code' => 0,
			'msg' => 'OK',
			'data' => array()
		);
		return response()->json($return);


	}


	/**
	 *
	 * 定时删除
	 */
	public function clearHeartBeat(Request $request)
	{

		$result = Rad_heart_beat::all();

		foreach($result as $value)
		{
			if(time() > strtotime($value->updated_at) + 50)
			{
				$value->delete();
			}
		}



	}






    
    //测试
    public function test(Request $request)
	{

        $radreply = Rad_users::where('user_id','>','1')->skip(0)->take(10)->get()->toArray();
	    return response($radreply);

	}

}
